package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.warning.domain.entity.*;
import com.ruoyi.warning.domain.vo.PortVO;
import com.ruoyi.warning.mapper.IndexMapper;
import com.ruoyi.warning.mapper.MempoolsMapper;
import com.ruoyi.warning.mapper.PortsMapper;
import com.ruoyi.warning.mapper.ProcessorsMapper;
import com.ruoyi.warning.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 告警模版表 服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-02-20
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private IDevicesLogService devicesLogService;
    @Resource
    private IMempoolsLogService mempoolsLogService;
    @Resource
    private IProcessorsLogService processorsLogService;
    @Resource
    private IEventService eventService;
    @Resource
    private IndexMapper indexMapper;
    @Resource
    private IDevicesService deviceService;
    @Resource
    private IPortsService portsService;
    @Resource
    private IServicesService servicesService;
    @Resource
    private ProcessorsMapper processorsMapper;
    @Resource
    private MempoolsMapper mempoolsMapper;
    @Resource
    private PortsMapper portMapper;
    @Resource
    private ICameraService cameraService;
    @Override
//    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void saveLog() {
        devicesLogService.refreshLog();
        mempoolsLogService.refreshLog();
        processorsLogService.refreshLog();
    }

    @Override
    public Object getWarningSituation(Integer level) {
        // 获取当前日期
        java.time.LocalDate today = java.time.LocalDate.now();
        // 获取今天的 0 点
        java.time.LocalDateTime todayStart = today.atStartOfDay();
        // 获取今天的 23 点 59 分 59 秒
        java.time.LocalDateTime todayEnd = today.atTime(23, 59, 59);
        // 获取七天前的 0 点
        java.time.LocalDateTime sevenDaysAgoStart = today.minusDays(6).atStartOfDay();
        // 过去7天的告警情况
        LambdaQueryWrapper<Event> wrapperSeven = new QueryWrapper<Event>().lambda()
                .ge(Event::getCreateTime, sevenDaysAgoStart)
                .le(Event::getCreateTime, todayEnd)
                .eq(level!=-1,Event::getEventLevel,level)
                ;
        // 今天的告警情况
        LambdaQueryWrapper<Event> wrapperToday = new QueryWrapper<Event>().lambda()
               .ge(Event::getCreateTime, todayStart)
               .le(Event::getCreateTime, todayEnd)
               .eq(level!=-1,Event::getEventLevel,level)
               ;
        HashMap<String,Object> map = new HashMap<>();
        map.put("today",eventService.count(wrapperToday));
        map.put("sevenDays",eventService.count(wrapperSeven));

        //过去7天的告警图表
        List<java.util.Map<String, Object>> list = indexMapper.getWarningSituation(level);
        map.put("list",list);
        return map;

    }

    @Override
    public Object getWarningScrollBar() {
        // 获取当前日期
        java.time.LocalDate now = java.time.LocalDate.now();
        java.time.LocalDateTime todayEnd = now.atTime(23, 59, 59);
        java.time.LocalDateTime twentyFourHoursAgo = java.time.LocalDateTime.now().minusHours(24);
        LambdaQueryWrapper<Event> wrapper = new QueryWrapper<Event>().lambda()
                .le(Event::getCreateTime, todayEnd)
                .ge(Event::getCreateTime, twentyFourHoursAgo)
                .orderByDesc(Event::getCreateTime)
                .last("limit 10")
                ;
        return eventService.list(wrapper);
    }

    @Override
    public Object getResourcesOverview() {
        HashMap<String,Integer> map = new HashMap<>();
        LambdaQueryWrapper<Device> wrapper = new QueryWrapper<Device>().lambda();
        List<Device> list = deviceService.list(wrapper);
        map.put("资源总量",list.size());
        map.put("已监控资源",list.stream()
                .filter(device -> device.getDisabled()==0)
                .collect(Collectors.toList()).size());
        map.put("在线资源",list.stream()
                .filter(device -> device.getStatus()==1)
                .collect(Collectors.toList()).size());
        map.put("离线资源",list.size()-map.get("在线资源"));
        map.put("网络设备",list.stream()
                .filter(device -> "network".equals(device.getType()))
                .collect(Collectors.toList()).size());
        map.put("服务器",list.stream()
                .filter(device -> "server".equals(device.getType()))
                .collect(Collectors.toList()).size());
        map.put("无线设备",list.stream()
                .filter(device -> "wireless".equals(device.getType()))
                .collect(Collectors.toList()).size());
        map.put("其他",list.size()-map.get("网络设备")-map.get("服务器")-map.get("无线设备"));
        return map;
    }

    @Override
    public Object getDeviceUsage() {
        // 取前五条
        List<Mempool> mempools = mempoolsMapper.getMaxfive();
        // 查询每个 DeviceId 对应的平均最大 ProcessorUsage，取前 5 条记录
        List<Processor> processors = processorsMapper.getMaxfive();
        DecimalFormat df = new DecimalFormat("#.00");
        List<PortVO> list = portMapper.getMaxfive().stream()
                .map(port -> {
                    //大于1000转Mbps，否则加上Kbps字符
                    if(Double.parseDouble(port.getBandwidthUtilization())>=1000){
                        if(Double.parseDouble(port.getBandwidthUtilization())/1000>=1000){
                            port.setBandwidthUtilization(df.format(Double.parseDouble(port.getBandwidthUtilization())/1000/1000)+"Gbps");
                        }else {
                            port.setBandwidthUtilization(df.format(Double.parseDouble(port.getBandwidthUtilization())/1000)+"Mbps");
                        }
                    }else {
                        port.setBandwidthUtilization(df.format(Double.parseDouble(port.getBandwidthUtilization()))+"Kbps");
                    }

                    if(Double.parseDouble(port.getInBandwidthUtilization())>=1000){
                        if(Double.parseDouble(port.getInBandwidthUtilization())/1000>=1000){
                            port.setInBandwidthUtilization(df.format(Double.parseDouble(port.getInBandwidthUtilization())/1000/1000)+"Gbps");
                        }else {
                            port.setInBandwidthUtilization(df.format(Double.parseDouble(port.getInBandwidthUtilization())/1000)+"Mbps");
                        }
                    }else {
                        port.setInBandwidthUtilization(df.format(Double.parseDouble(port.getInBandwidthUtilization()))+"Kbps");
                    }

                    if(Double.parseDouble(port.getOutBandwidthUtilization())>=1000){
                        if(Double.parseDouble(port.getOutBandwidthUtilization())/1000>=1000){
                            port.setOutBandwidthUtilization(df.format(Double.parseDouble(port.getOutBandwidthUtilization())/1000/1000)+"Gbps");
                        }else {
                            port.setOutBandwidthUtilization(df.format(Double.parseDouble(port.getOutBandwidthUtilization())/1000)+"Mbps");
                        }
                    }else {
                        port.setOutBandwidthUtilization(df.format(Double.parseDouble(port.getOutBandwidthUtilization()))+"Kbps");
                    }

                    return port;
                })
                .collect(Collectors.toList());

        HashMap<String,Object> map = new HashMap<>();
        map.put("内存池",mempools);
        map.put("处理器",processors);
        map.put("端口",list);
        return map;
    }

    @Override
    public Object getStatistics() {
        HashMap<String,Integer> map = new HashMap<>();
        List<Device> deviceList = deviceService.list();
        map.put("设备总数",deviceList.size());
        map.put("在线设备",deviceList.stream()
                .filter(device -> device.getStatus()==1)
                .collect(Collectors.toList()).size());
        map.put("离线设备",deviceList.stream()
                .filter(device -> device.getStatus()==0)
                .collect(Collectors.toList()).size());
        map.put("监控设备",deviceList.stream()
                .filter(device -> device.getDisabled()==0)
                .collect(Collectors.toList()).size());

//        List<Integer> deviceIds = deviceList.stream()
//                .map(Device::getDeviceId).collect(Collectors.toList());
//        List<Port> portList = portsService.list(new QueryWrapper<Port>().lambda()
//                .in(Port::getDeviceId,deviceIds));
//        map.put("端口总数",portList.size());
//        map.put("在线端口",portList.stream()
//                .filter(port -> "up".equals(port.getIfOperStatus()))
//                .collect(Collectors.toList()).size());
//        map.put("离线端口",portList.stream()
//                .filter(port -> "down".equals(port.getIfOperStatus()))
//                .collect(Collectors.toList()).size());
//        map.put("监控端口",portList.stream()
//                .filter(port -> port.getIgnore()==0)
//                .collect(Collectors.toList()).size());

        List<com.ruoyi.warning.domain.entity.Service> serviceList = servicesService.list();
        map.put("服务总数",serviceList.size());
        map.put("在线服务",serviceList.stream()
                .filter(service -> service.getServiceStatus()==0)
                .collect(Collectors.toList()).size());
        map.put("离线服务",serviceList.stream()
                .filter(service -> service.getServiceStatus()!=0)
                .collect(Collectors.toList()).size());
        map.put("监控服务",serviceList.stream()
                .filter(service -> service.getServiceDisabled())
                .collect(Collectors.toList()).size());

        List<Camera> cameraList = cameraService.list();
        map.put("监控总数",cameraList.size());
        map.put("在线监控",cameraList.stream()
                .filter(camera -> "1".equals(camera.getOnlineStatus()))
                .collect(Collectors.toList()).size());
        map.put("离线监控",cameraList.stream()
                .filter(camera -> "0".equals(camera.getOnlineStatus()))
                .collect(Collectors.toList()).size());

        return map;
    }

    @Override
    public Object getDeviceStatistics() {
        List<Map<String, String>> deviceList = indexMapper.getDeviceStatistics();
        List<Map<String, String>> systemList = indexMapper.getSystemStatistics();
        Map<String,Object> map = new HashMap<>();
        map.put("小类",deviceList);
        map.put("大类",systemList);
        return map;
    }

}
